/**
 * This class contains utility methods that aids in the spelling process.
 * @author David Emole
 */
package com.spell;

public class SpellUtils {

	public static String normalize(String numberString){
		//special case: negative number
		boolean isNegative = numberString.charAt(0) == '-';
		numberString = numberString.substring(numberString.indexOf('-') + 1); //assumes a return of -1 if char not found

		//check for decimal with an empty wholepart: change ".9" to "0.9"
		numberString = numberString.replaceFirst("^\\.", "0."); 
		
		String normalizedNumberString = removeLeadingZeros(removeTrailingDecimalZeros(removeCommas(numberString)));
		return (isNegative ? ("-" + normalizedNumberString) : normalizedNumberString);
	}
	
	public static String removeCommas(String str){
		return str.replace(",", "");
	}
	
	public static String removeTrailingDecimalZeros(String str){
		//If it is a valid decimal number, find and replace trailing zeros with empty string
		if(str.matches("-?\\d*\\.\\d+")) 
			return str.replaceAll("\\.?0+(?=$)", "");
		else 
			return str;
	}
	
	public static String removeLeadingZeros(String str){
		return str.replaceFirst("^0+(?=[1-9])", "");
	}

	public static String capitalizeFirstLetter(String str){
		return str.replaceFirst(str.substring(0,1), str.substring(0,1).toUpperCase());
	}

	public static String addCommas(String str){
		//special case: negative number
		boolean isNegative = str.charAt(0) == '-';
		str = str.substring(str.indexOf('-') + 1); //assumes a return of -1 if char not found

		int len = str.length();
		String withCommas = (len <= 3) ? str :
			(addCommas(str.substring(0, len - 3)) + "," + str.substring(len - 3));
		return isNegative ? ("-" + withCommas) : withCommas;
	}
	
}
